// 真实环境系统 - 专门处理真实的墙壁和爆炸桶
(function() {
    'use strict';
    
    console.log('🏗️ 真实环境系统启动...');
    
    class RealisticEnvironment {
        constructor() {
            this.objects = [];
            this.initialized = false;
            this.gameReady = false;
            this.renderActive = false;
            
            // 延迟启动，确保游戏完全加载
            setTimeout(() => this.initialize(), 8000);
        }
        
        initialize() {
            console.log('🏗️ 真实环境初始化...');
            
            this.waitForGame();
        }
        
        waitForGame() {
            let attempts = 0;
            const check = () => {
                attempts++;
                
                try {
                    if (window.gameEngine && 
                        window.gameEngine.gameState &&
                        window.levelManager && 
                        window.player) {
                        
                        console.log('✅ 游戏系统检测完成，开始创建真实环境');
                        this.gameReady = true;
                        this.startEnvironmentSystem();
                        return;
                    }
                } catch (error) {
                    // 继续等待
                }
                
                if (attempts < 20) {
                    setTimeout(check, 1000);
                } else {
                    console.log('⚠️ 游戏检测超时，环境系统跳过');
                }
            };
            
            check();
        }
        
        startEnvironmentSystem() {
            console.log('🌍 启动环境系统...');
            
            // 等待关卡真正开始
            this.waitForLevelStart();
            
            // 启动安全的渲染系统
            this.startSafeRendering();
            
            // 启动碰撞检测
            this.startCollisionSystem();
        }
        
        waitForLevelStart() {
            const checkLevel = setInterval(() => {
                try {
                    if (window.gameEngine.gameState === 'playing' && 
                        window.levelManager.currentLevel > 0) {
                        
                        console.log('🎮 关卡开始，创建环境对象');
                        this.createRealisticObjects();
                        clearInterval(checkLevel);
                    }
                } catch (error) {
                    // 继续等待
                }
            }, 1000);
        }
        
        createRealisticObjects() {
            this.objects = [];
            
            // 创建真实的墙壁
            this.createWalls();
            
            // 创建真实的桌子
            this.createTables();
            
            // 创建真实的爆炸桶
            this.createBarrels();
            
            this.initialized = true;
            console.log(`✅ 创建了 ${this.objects.length} 个真实环境对象`);
        }
        
        createWalls() {
            // 创建一些装饰性墙壁 (不影响游戏碰撞)
            const walls = [
                { x: 100, y: 150, width: 20, height: 100, type: 'wall_vertical' },
                { x: 800, y: 200, width: 20, height: 120, type: 'wall_vertical' },
                { x: 300, y: 100, width: 150, height: 20, type: 'wall_horizontal' },
                { x: 500, y: 600, width: 200, height: 20, type: 'wall_horizontal' }
            ];
            
            walls.forEach(wall => {
                wall.health = 5;
                wall.maxHealth = 5;
                wall.destroyed = false;
                this.objects.push(wall);
            });
        }
        
        createTables() {
            // 创建真实的桌子
            for (let i = 0; i < 3; i++) {
                this.objects.push({
                    x: Math.random() * 500 + 250,
                    y: Math.random() * 300 + 250,
                    width: 80,
                    height: 50,
                    type: 'realistic_table',
                    health: 3,
                    maxHealth: 3,
                    destroyed: false
                });
            }
        }
        
        createBarrels() {
            // 创建真实的爆炸桶
            for (let i = 0; i < 2; i++) {
                this.objects.push({
                    x: Math.random() * 400 + 300,
                    y: Math.random() * 200 + 300,
                    width: 40,
                    height: 50,
                    type: 'realistic_barrel',
                    health: 1,
                    maxHealth: 1,
                    destroyed: false,
                    explosive: true
                });
            }
        }
        
        startSafeRendering() {
            // 使用独立的渲染循环，不干扰原游戏
            setInterval(() => {
                try {
                    if (this.gameReady && 
                        this.initialized && 
                        window.gameEngine && 
                        window.gameEngine.ctx &&
                        window.gameEngine.gameState === 'playing') {
                        
                        this.renderEnvironment(window.gameEngine.ctx);
                    }
                } catch (error) {
                    // 静默处理渲染错误
                }
            }, 16);
        }
        
        renderEnvironment(ctx) {
            // 保存当前绘制状态
            ctx.save();
            
            // 渲染所有环境对象
            this.objects.forEach(obj => {
                if (!obj.destroyed) {
                    this.renderObject(ctx, obj);
                }
            });
            
            // 恢复绘制状态
            ctx.restore();
        }
        
        renderObject(ctx, obj) {
            switch (obj.type) {
                case 'wall_vertical':
                case 'wall_horizontal':
                    this.drawRealisticWall(ctx, obj);
                    break;
                case 'realistic_table':
                    this.drawRealisticTable(ctx, obj);
                    break;
                case 'realistic_barrel':
                    this.drawRealisticBarrel(ctx, obj);
                    break;
            }
        }
        
        drawRealisticWall(ctx, wall) {
            // 绘制真实的墙壁
            ctx.save();
            
            // 主体颜色 - 砖墙效果
            const gradient = ctx.createLinearGradient(
                wall.x, wall.y, 
                wall.x + wall.width, wall.y + wall.height
            );
            gradient.addColorStop(0, '#8B4513');
            gradient.addColorStop(0.3, '#A0522D');
            gradient.addColorStop(0.7, '#CD853F');
            gradient.addColorStop(1, '#DEB887');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(wall.x, wall.y, wall.width, wall.height);
            
            // 砖块纹理
            ctx.strokeStyle = '#654321';
            ctx.lineWidth = 1;
            
            if (wall.type === 'wall_vertical') {
                // 竖直墙壁的砖块
                for (let y = wall.y; y < wall.y + wall.height; y += 20) {
                    ctx.beginPath();
                    ctx.moveTo(wall.x, y);
                    ctx.lineTo(wall.x + wall.width, y);
                    ctx.stroke();
                }
            } else {
                // 水平墙壁的砖块
                for (let x = wall.x; x < wall.x + wall.width; x += 25) {
                    ctx.beginPath();
                    ctx.moveTo(x, wall.y);
                    ctx.lineTo(x, wall.y + wall.height);
                    ctx.stroke();
                }
            }
            
            // 边框
            ctx.strokeStyle = '#2F1B14';
            ctx.lineWidth = 2;
            ctx.strokeRect(wall.x, wall.y, wall.width, wall.height);
            
            // 损坏效果
            if (wall.health < wall.maxHealth) {
                ctx.fillStyle = 'rgba(139, 69, 19, 0.6)';
                ctx.fillRect(wall.x + 2, wall.y + 2, wall.width - 4, wall.height - 4);
                
                // 裂痕
                ctx.strokeStyle = '#000000';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.moveTo(wall.x + wall.width * 0.1, wall.y + wall.height * 0.2);
                ctx.lineTo(wall.x + wall.width * 0.9, wall.y + wall.height * 0.8);
                ctx.stroke();
            }
            
            ctx.restore();
        }
        
        drawRealisticTable(ctx, table) {
            ctx.save();
            
            // 桌面渐变
            const tableGradient = ctx.createLinearGradient(
                table.x, table.y, 
                table.x + table.width, table.y + table.height
            );
            tableGradient.addColorStop(0, '#D2691E');
            tableGradient.addColorStop(0.3, '#CD853F');
            tableGradient.addColorStop(0.7, '#8B4513');
            tableGradient.addColorStop(1, '#654321');
            
            ctx.fillStyle = tableGradient;
            ctx.fillRect(table.x, table.y, table.width, table.height);
            
            // 桌面木纹
            ctx.strokeStyle = '#654321';
            ctx.lineWidth = 1;
            for (let i = 0; i < 3; i++) {
                const y = table.y + (table.height / 4) * (i + 1);
                ctx.beginPath();
                ctx.moveTo(table.x + 5, y);
                ctx.lineTo(table.x + table.width - 5, y);
                ctx.stroke();
            }
            
            // 桌腿
            const legWidth = 6;
            const legHeight = 12;
            ctx.fillStyle = '#654321';
            
            // 四个桌腿
            const positions = [
                [table.x + 5, table.y + table.height],
                [table.x + table.width - legWidth - 5, table.y + table.height],
                [table.x + 5, table.y + table.height - 8],
                [table.x + table.width - legWidth - 5, table.y + table.height - 8]
            ];
            
            positions.forEach(([x, y]) => {
                ctx.fillRect(x, y, legWidth, legHeight);
            });
            
            // 高光效果
            const highlight = ctx.createLinearGradient(
                table.x, table.y, 
                table.x + table.width/2, table.y
            );
            highlight.addColorStop(0, 'rgba(255, 255, 255, 0.2)');
            highlight.addColorStop(1, 'rgba(255, 255, 255, 0)');
            
            ctx.fillStyle = highlight;
            ctx.fillRect(table.x, table.y, table.width/2, table.height);
            
            // 边框
            ctx.strokeStyle = '#2F1B14';
            ctx.lineWidth = 2;
            ctx.strokeRect(table.x, table.y, table.width, table.height);
            
            // 损坏效果
            if (table.health < table.maxHealth) {
                ctx.fillStyle = 'rgba(101, 67, 33, 0.5)';
                ctx.fillRect(table.x + 8, table.y + 8, table.width - 16, table.height - 16);
                
                // 破损裂痕
                ctx.strokeStyle = '#2F1B14';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.moveTo(table.x + table.width * 0.2, table.y + table.height * 0.2);
                ctx.lineTo(table.x + table.width * 0.8, table.y + table.height * 0.7);
                ctx.moveTo(table.x + table.width * 0.6, table.y + table.height * 0.1);
                ctx.lineTo(table.x + table.width * 0.3, table.y + table.height * 0.9);
                ctx.stroke();
            }
            
            ctx.restore();
        }
        
        drawRealisticBarrel(ctx, barrel) {
            ctx.save();
            
            // 桶身金属渐变
            const barrelGradient = ctx.createRadialGradient(
                barrel.x + barrel.width/2, barrel.y + barrel.height/3, 5,
                barrel.x + barrel.width/2, barrel.y + barrel.height/2, barrel.width
            );
            barrelGradient.addColorStop(0, '#FF4500');
            barrelGradient.addColorStop(0.3, '#DC143C');
            barrelGradient.addColorStop(0.6, '#B22222');
            barrelGradient.addColorStop(0.8, '#8B0000');
            barrelGradient.addColorStop(1, '#4B0000');
            
            ctx.fillStyle = barrelGradient;
            ctx.fillRect(barrel.x, barrel.y, barrel.width, barrel.height);
            
            // 金属环带
            ctx.strokeStyle = '#696969';
            ctx.lineWidth = 3;
            for (let i = 1; i <= 4; i++) {
                const y = barrel.y + (barrel.height / 5) * i;
                ctx.beginPath();
                ctx.moveTo(barrel.x, y);
                ctx.lineTo(barrel.x + barrel.width, y);
                ctx.stroke();
            }
            
            // 金属环的高光
            ctx.strokeStyle = '#A9A9A9';
            ctx.lineWidth = 1;
            for (let i = 1; i <= 4; i++) {
                const y = barrel.y + (barrel.height / 5) * i - 1;
                ctx.beginPath();
                ctx.moveTo(barrel.x, y);
                ctx.lineTo(barrel.x + barrel.width, y);
                ctx.stroke();
            }
            
            // 危险标志背景
            ctx.fillStyle = '#FFD700';
            ctx.fillRect(
                barrel.x + barrel.width/2 - 12, 
                barrel.y + barrel.height/2 - 8, 
                24, 16
            );
            
            // 危险标志
            ctx.fillStyle = '#FF0000';
            ctx.font = 'bold 16px monospace';
            ctx.textAlign = 'center';
            ctx.fillText('⚠', barrel.x + barrel.width/2, barrel.y + barrel.height/2 + 5);
            
            // 反光效果
            const highlight = ctx.createLinearGradient(
                barrel.x, barrel.y, 
                barrel.x + barrel.width/3, barrel.y + barrel.height/2
            );
            highlight.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
            highlight.addColorStop(0.5, 'rgba(255, 255, 255, 0.2)');
            highlight.addColorStop(1, 'rgba(255, 255, 255, 0)');
            
            ctx.fillStyle = highlight;
            ctx.fillRect(barrel.x, barrel.y, barrel.width/3, barrel.height);
            
            // 边框阴影
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 1;
            ctx.strokeRect(barrel.x + 1, barrel.y + 1, barrel.width, barrel.height);
            
            // 主边框
            ctx.strokeStyle = '#2F1B14';
            ctx.lineWidth = 2;
            ctx.strokeRect(barrel.x, barrel.y, barrel.width, barrel.height);
            
            ctx.restore();
        }
        
        startCollisionSystem() {
            setInterval(() => {
                try {
                    if (this.gameReady && 
                        this.initialized &&
                        window.gameEngine && 
                        window.gameEngine.bullets &&
                        window.gameEngine.gameState === 'playing') {
                        
                        this.checkCollisions();
                    }
                } catch (error) {
                    // 静默处理碰撞检测错误
                }
            }, 50);
        }
        
        checkCollisions() {
            if (!window.gameEngine.bullets) return;
            
            window.gameEngine.bullets.forEach((bullet, bulletIndex) => {
                this.objects.forEach(obj => {
                    if (!obj.destroyed && this.isColliding(bullet, obj)) {
                        // 安全移除子弹
                        try {
                            window.gameEngine.bullets.splice(bulletIndex, 1);
                        } catch (error) {
                            // 移除失败也没关系
                        }
                        
                        // 伤害物品
                        obj.health--;
                        console.log(`💥 击中 ${obj.type}, 剩余血量: ${obj.health}`);
                        
                        if (obj.health <= 0) {
                            obj.destroyed = true;
                            
                            if (obj.explosive) {
                                this.createExplosion(obj);
                            } else {
                                this.createDebris(obj);
                            }
                        }
                    }
                });
            });
        }
        
        createExplosion(barrel) {
            console.log('💥 真实爆炸桶爆炸！');
            
            // 创建爆炸粒子
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    for (let i = 0; i < 20; i++) {
                        const angle = (Math.PI * 2 * i) / 20;
                        const speed = Math.random() * 200 + 100;
                        
                        window.gameEngine.particles.push({
                            x: barrel.x + barrel.width/2,
                            y: barrel.y + barrel.height/2,
                            vx: Math.cos(angle) * speed,
                            vy: Math.sin(angle) * speed,
                            life: Math.random() * 2 + 1,
                            maxLife: Math.random() * 2 + 1,
                            color: ['#FF4500', '#FF6347', '#FFD700', '#DC143C', '#FF8C00'][Math.floor(Math.random() * 5)],
                            size: Math.random() * 10 + 5
                        });
                    }
                }
            } catch (error) {
                // 粒子创建失败也没关系
            }
            
            // 爆炸视觉效果
            this.showExplosionEffect();
        }
        
        showExplosionEffect() {
            const explosion = document.createElement('div');
            explosion.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: radial-gradient(circle, rgba(255,69,0,0.7) 0%, rgba(255,99,71,0.3) 30%, transparent 70%);
                pointer-events: none; z-index: 6000;
            `;
            
            document.body.appendChild(explosion);
            
            let opacity = 0.7;
            const fade = setInterval(() => {
                opacity -= 0.05;
                explosion.style.opacity = opacity;
                
                if (opacity <= 0) {
                    clearInterval(fade);
                    try {
                        if (explosion.parentNode) {
                            document.body.removeChild(explosion);
                        }
                    } catch (error) {
                        // 移除失败也没关系
                    }
                }
            }, 30);
        }
        
        createDebris(obj) {
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    const colors = obj.type.includes('wall') ? 
                        ['#8B4513', '#A0522D', '#654321'] : 
                        ['#D2691E', '#8B4513', '#654321'];
                    
                    for (let i = 0; i < 10; i++) {
                        window.gameEngine.particles.push({
                            x: obj.x + Math.random() * obj.width,
                            y: obj.y + Math.random() * obj.height,
                            vx: (Math.random() - 0.5) * 150,
                            vy: (Math.random() - 0.5) * 150,
                            life: Math.random() * 2 + 1,
                            maxLife: Math.random() * 2 + 1,
                            color: colors[Math.floor(Math.random() * colors.length)],
                            size: Math.random() * 6 + 3
                        });
                    }
                }
            } catch (error) {
                // 碎片创建失败也没关系
            }
        }
        
        isColliding(bullet, obj) {
            const bx = bullet.x - (bullet.radius || 3);
            const by = bullet.y - (bullet.radius || 3);
            const bw = (bullet.radius || 3) * 2;
            const bh = (bullet.radius || 3) * 2;
            
            return bx < obj.x + obj.width &&
                   bx + bw > obj.x &&
                   by < obj.y + obj.height &&
                   by + bh > obj.y;
        }
    }
    
    // 安全启动
    try {
        window.realisticEnvironment = new RealisticEnvironment();
        console.log('✅ 真实环境系统已加载');
    } catch (error) {
        console.error('❌ 真实环境系统加载失败:', error);
    }
    
})();